import { ABP, ListService } from '@abp/ng.core';
import { Component, Input, OnInit } from '@angular/core';
import { NzModalRef } from 'ng-zorro-antd/modal';
import snq from 'snq';
import { ListComponent } from './list.component';

@Component({
  selector: '',
  template: ``,
})
export abstract class RefEntityListComponent<T extends { id: string }>
  extends ListComponent
  implements OnInit
{
  models: T[] = [];
  totalCount: number = 0;

  @Input() selectedModels: T[] = [];
  @Input() selectMode: 'single' | 'multiple' = 'single';

  constructor(
    public readonly listService: ListService<ABP.PageQueryParams>,
    public modalRef: NzModalRef
  ) {
    super(listService);
  }

  isModelSelected(item: T) {
    return !!snq(() => this.selectedModels.find(x => x.id == item.id));
  }

  setCurrentModel(item: T) {
    if (this.selectMode == 'single') {
      if (!this.selectedModels?.length) {
        this.selectedModels = [item];
      } else {
        if (this.selectedModels[0] == item) this.selectedModels = [];
        else this.selectedModels = [item];
      }
    } else {
      if (this.isModelSelected(item)) {
        this.selectedModels = snq(() => this.selectedModels.filter(x => x.id != item.id));
      } else {
        this.selectedModels = [...snq(() => this.selectedModels), item];
      }
    }
  }

  setCurrentModelAndSubmit(item: T) {
    if (this.selectMode == 'single') {
      this.selectedModels = [item];
      this.submitForm();
    } else {
      if (this.isModelSelected(item)) {
        this.selectedModels = snq(() => this.selectedModels.filter(x => x.id != item.id));
      } else {
        this.selectedModels = [...snq(() => this.selectedModels), item];
      }
    }
  }

  cancelForm() {
    this.modalRef.close(null);
  }

  submitForm() {
    var selectedModels = !this.selectedModels?.length ? null : this.selectedModels;
    this.modalRef.close(selectedModels);
  }

  ngOnInit(): void {
    this.hookToQuery().then(result => {
      this.models = result.items;
      this.totalCount = result.totalCount;
    });
  }
}
